<template>
  <div class="approver">
    <div class="approver-item" v-for="(item, index) in approver" :key="index">
      <div class="approver-item-c">
        <el-avatar :src="url + item.avatar"></el-avatar>
        <el-tag
          type="success"
          closable
          @close="handleDelOpportunitiesApprover(index)"
          >{{ item.showName || item.approvalName || item.userName }}
        </el-tag>
        <div v-if="!isCc">第{{ item.approvalLevel }}级审批人</div>
        <template
          v-if="
            !isCc &&
            typeof item.state === 'number' &&
            item.state !== 0 &&
            !isEdit
          "
        >
          <div>{{ item.byTheDate }}</div>
          <div>审批意见：{{ item.approvalOpinion }}</div>
        </template>
      </div>
      <div v-if="!isCc && index !== approver.length - 1">
        <el-icon><Right /></el-icon>
      </div>
    </div>
    <div v-if="!readonly">
      <el-button
        link
        type="primary"
        round
        @click="
          approverDialog = true;
          handleAddPeople();
        "
        style="position: relative; top: -3px; left: -10px"
      >
        {{ isCc ? "添加抄送人" : "添加审批人" }}
      </el-button>
    </div>
    <el-dialog
      :title="addTitle"
      v-model="approverDialog"
      :close-on-click-modal="false"
      :before-close="handleClose"
      append-to-body
      width="70%"
    >
      <div class="approver-inquiry">
        <el-form :model="groupParams" ref="ruleForm" style="display: flex">
          <el-form-item label="员工姓名" prop="showName">
            <el-input
              class="filter-item"
              v-model="groupParams.nickName"
              :clearable="true"
              placeholder="员工姓名"
            />
          </el-form-item>
          <el-form-item label="所属部门" style="margin-left: 10px">
            <el-cascader
              class="input-item"
              v-model="groupParams.deptId"
              :clearable="true"
              placeholder="所属部门"
              :props="dropdownprops"
              :options="dropdownList"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item style="margin-left: 10px">
            <el-button type="primary" @click="onSubmit" :icon="Search"
              >查询</el-button
            >
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
          :data="groupList"
          header-cell-class-name="table-header-gray"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column label="用户名" prop="userName"> </el-table-column>
          <el-table-column label="员工姓名" prop="nickName"> </el-table-column>
          <el-table-column label="部门" prop="dept.deptName"> </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="100"
          >
            <template #default="scope">
              <el-button
                type="primary"
                @click="handleChooseapprover(scope.row)"
                v-if="!scope.row.check"
                >选择</el-button
              >
              <el-button
                type="primary"
                @click="handleCancelapprover(scope.row, scope.$index)"
                v-if="scope.row.check"
                >取消</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 20px">
          <el-pagination
            background
            @size-change="handleSizeChangeGroup"
            @current-change="handleCurrentChangeGroup"
            :current-page="groupParams.pageNo"
            :page-size="groupParams.page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="groupTotal"
          ></el-pagination>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script  setup>
import headerImgSrc from "@/assets/images/default-header.png";
import { reactive } from "vue";
import { selectsPeople, deptNameApi } from "@/api/project/conversion";
const stateNameArr = ["待审核", "审核通过", "审核驳回"];
const addTitle = ref("添加审批人");
const url = import.meta.env.VITE_APP_BASE_API;
const groupList = ref([]);
const approverDialog = ref(false);
const approver = ref([]);
const groupTotal = ref(0);
const groupParams = reactive({
  showName: "",
  deptId: "",
});
let dropdownprops = {
  value: "deptId",
  label: "deptName",
  emitPath: false,
};

const check = ref(true);

const props = defineProps({
  // 请求用户列表的函数
  getUserFn: {
    type: Function,
    default: () => {},
  },
  // 审批人类型，1-商机任务;3-项目立项;4-项目任务;21-盖章申请;22-用车审批;23-投标审批;24-合同盖章审批;25-资质盖章审批;50-合同盖章;52-合同会审
  typeId: {
    default: undefined,
  },
  // 是否为抄送
  isCc: {
    type: Boolean,
    default: false,
  },
  // 回显的话为true
  readonly: {
    type: Boolean,
    default: false,
  },
});

const dropdownList = ref([]);

// 所属部门名称
const deptNameRole = async () => {
  try {
    let params = {};
    const response = await deptNameApi(params);
    if (response.code === 200 && response.data.length >= 0) {
      dropdownList.value = response.data;
    }
  } catch (err) {
    console.log(err);
  }
};
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);
// 查询功能
const approverData = async () => {
  try {
    let params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      nickName: groupParams.nickName,
      deptId: groupParams.deptId,
    };
    const response = await selectsPeople(params);
    if (response.code === 200 && response.rows.length >= 0) {
      groupList.value = response.rows;
      //有已选择数据：找到相同的数据，将已选择数据中的状态赋值给弹窗列表的状态
      if (approver.value.length) {
        // 找到相同的数据的数组
        console.log(approver.value);
        approver.value.forEach((item) => {
          const selectUser = groupList.value.find(
            (it) => it.userId === item.userId
          );
          // @ts-ignore
          selectUser.check = true;
        });
      }
      total.value = Number(response.total);
    }
  } catch (err) {
    console.log(err);
  }
};

// 审批人选择
const handleChooseapprover = (row) => {
  row.check = true;
  // 选择之后，带到审批人列表
  approver.value.push({
    approvalLevel: approver.value ? approver.value.length + 1 : 1,
    approvalName: row.nickName,
    userId: row.userId,
    avatar: row.avatar,
  });
  let userIds = approver.value.map((item) => item.userId);
  // 2.添加过的数据不再重复添加
  emit("handleChooseapprover", userIds);
};

// 审批人取消
const handleCancelapprover = (row, index) => {
  row.check = false;
  // 删除当前条数据
  approver.value.splice(index, 1);
  emit("handleCancelapprover", row, index);
};

// 查询
const onSubmit = () => {
  approverData();
};

// 重置
const reset = () => {
  groupParams.nickName = "";
  groupParams.deptId = "";
  approverData();
};

const handleAddPeople = () => {
  if (props.isCc) {
    addTitle.value = "添加抄送人";
  } else {
    addTitle.value = "添加审批人";
  }
};
// 1.按钮保存隐藏
// const hasButton = () => {
//   if (route.query.name === "3") {
//     hasButtonSave.value = false;
//   } else {
//     hasButtonSave.value = true;
//   }
// };

const emit = defineEmits([
  "handleChooseapprover",
  "handleCancelapprover",
  "approverData",
]);

// 移除
const handleDelOpportunitiesApprover = (index) => {
  // 删除当前条数据
  approver.value.splice(index, 1);
  // 级别
  approver.value.forEach((item, i) => {
    item.approvalLevel = i + 1;
  });
  emit("handleChooseapprover", approver.value);
};

const handleClose = () => {
  approverDialog.value = false;
  groupParams.nickName = "";
  groupParams.deptId = "";
};

onMounted(async () => {
  // hasButton();
  await approverData();
  await deptNameRole();
});
</script>
<style lang="scss" scoped>
.approver {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  background: #fff;
  .approver-item {
    display: flex;
    justify-content: space-between;
    .approver-item-c {
      padding: 0 10px;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      & > * {
        margin: 5px 0;
      }
    }
  }

  :deep(.el-form-item__content) {
    display: flex;
  }
}
</style>
